import { App, Inject, Provide } from '@midwayjs/decorator'
import { Application } from 'egg'
import { gql } from 'graphql-request'

import { SystemUserService } from './system-user'

const TemplateFragment = `
  id
  department {
    id
    name
  }
  attachment: ie_attachment {
    id
    filename
    filepath
    ext
    create_at
  }
  bookmarks
  create_at
`

@Provide()
export class TemplateService {

  @App()
  app: Application

  @Inject()
  systemUserService: SystemUserService

  async get(id) {
    try {
      const { template_by_pk } = await this.app.gqlRequest(gql`
        query ($id: Int!) {
          template_by_pk (id: $id) {
            ${TemplateFragment}
          }
        }
      `, { id })

      return template_by_pk
    } catch (err) {}
  }

  async add(template) {
    const {
      create_by_id,
      ...object
    } = template

    try {
      const create_by = await this.systemUserService.get({ id: create_by_id })

      // 自动设置模板归属部门为生成模板人所在部门
      if (create_by?.system_user_meta?.department?.id) {
        object.department_id = create_by.system_user_meta.department.id
      }

      const {
        insert_template_one
      } = await this.app.gqlRequest(gql`
        mutation ($object: template_insert_input!) {
          insert_template_one (object: $object) {
            ${TemplateFragment}
          }
        }
      `, { object })

      return insert_template_one
    } catch (err) {}
  }
}